package com.chen.service.Impl;


import cn.hutool.core.util.StrUtil;
import com.chen.enums.Enums;
import com.chen.mapper.StuDao;
import com.chen.pojo.Stu;
import com.chen.pojo.beans.CommonResult;
import com.chen.pojo.model.ListQueryUser;
import com.chen.pojo.model.StuModel;
import com.chen.service.StuService;
import com.chen.utils.PageUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service("stuService")
public class StuServiceImpl implements StuService {

    @Resource
    private StuDao stuDao;


    @Override
    public CommonResult getPage(ListQueryUser listQueryUser) {
        List<Stu> list = stuDao.getList(listQueryUser.getName(),
                listQueryUser.getSex(),
                listQueryUser.getAge(),
                listQueryUser.getAddress(),
                listQueryUser.getNumber());
        // 判断前台带入的当前用户名
        List<Stu> stus = filterList(list, listQueryUser);
        PageUtils<StuModel> page = new PageUtils<StuModel>();
        page.initPage(formatUserToUserModel(stus), listQueryUser.getCurrentPage(), listQueryUser.getPageSize());

        return new CommonResult(Enums.SUCCESS, page);
    }

    private List<Stu> filterList(List<Stu> list, ListQueryUser listQueryUser) {
        List<Stu> newList = new ArrayList<>();
        //当前用户
        String currentUserNo = listQueryUser.getCurrentUser();
        // 当为admin用户的时候显示所有信息
        if ("admin".equals(currentUserNo)) {
            return list;
        } else {
            for (Stu stu : list) {
                if ( StrUtil.isNotEmpty(stu.getFounder()) && stu.getFounder().equals(currentUserNo)) {
                    newList.add(stu);
                }
            }

            return newList;
        }
    }

    private List<StuModel> formatUserToUserModel(List<Stu> list) {
        List<StuModel> models = new ArrayList<>();
        for (Stu user : list) {
            StuModel model = new StuModel(user);
            models.add(model);
        }
        return models;
    }

    @Override
    public int deleteByPrimaryKey(Integer id) {
        return stuDao.deleteByPrimaryKey(id);
    }

    @Override
    public int insert(Stu record) {
        return stuDao.insert(record);
    }

    @Override
    public int insertSelective(Stu record) {
        return stuDao.insertSelective(record);
    }

    @Override
    public Stu selectByPrimaryKey(Integer id) {
        return stuDao.selectByPrimaryKey(id);
    }

    @Override
    public int updateByPrimaryKeySelective(Stu record) {
        return stuDao.updateByPrimaryKeySelective(record);
    }

    @Override
    public int updateByPrimaryKey(Stu record) {
        return stuDao.updateByPrimaryKey(record);
    }
}
